package com.ting.log.core;

import com.ting.common.exception.TingBaseException;
import com.ting.common.utils.UserInfoUtils;
import com.ting.common.vo.UserBaseModel;
import com.ting.log.annotation.OperateLog;
import com.ting.log.db.LogOperateService;
import com.ting.log.dto.LogOperateSaveDTO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zifang
 */
@Aspect
@Component
@Slf4j
public class OperateLogAspectj {

    @Autowired
    UserInfoUtils userInfoUtils;
    @Autowired
    LogOperateService logOperateService;
    @Autowired
    HttpServletRequest request;

    @Pointcut("@annotation(com.ting.log.annotation.OperateLog)")
    public void operateLogPointCut() {
    }

    @Around("operateLogPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        OperateLog operateLog = signature.getMethod().getAnnotation(OperateLog.class);
        String operateName = operateLog.operateName();
        LogOperateSaveDTO operateSaveDTO = new LogOperateSaveDTO();
        operateSaveDTO.setOperationName(operateName);
        operateSaveDTO.setResult(true);
        try {
            return point.proceed();
        }catch (TingBaseException e){
            operateSaveDTO.setResult(false);
            operateSaveDTO.setErrorMsg(e.getMessage());
            log.error("",e);
            throw new TingBaseException(e.getCode(),e.getMessage());
        }catch (Exception e){
            operateSaveDTO.setResult(false);
            operateSaveDTO.setErrorMsg(e.getMessage());
            log.error("",e);
            throw new Exception(e);
        }finally {
            saveLog(operateSaveDTO);
        }

    }

    public void saveLog(LogOperateSaveDTO operateSaveDTO){
        UserBaseModel userBaseModel = userInfoUtils.tryGetUser();
        if (!ObjectUtils.isEmpty(userBaseModel)){
            operateSaveDTO.setUserId(userBaseModel.getId());
            operateSaveDTO.setUserName(userBaseModel.getUserName());
        }
        logOperateService.buildRequestInfo(operateSaveDTO);
        logOperateService.saveLogAsync(operateSaveDTO);
    }
}
